<template>
  <div class="login-container" @copy.prevent @contextmenu.prevent>
    <div class="login-box">
      <div class="logo-container">
        <div class="logo-wrapper">
          <div class="logo">
            <div class="z-logo">
              <div class="z-line z-top"></div>
              <div class="z-line z-middle"></div>
              <div class="z-line z-bottom"></div>
            </div>
          </div>
        </div>
        <h1 class="title">咸阳北站自动化ETC</h1>
        <p class="subtitle">欢迎登录系统</p>
      </div>
      <div class="login-form">
        <div class="form-item">
          <span class="icon-wrapper">
            <UserOutlined />
          </span>
          <input
            ref="usernameInput"
            v-model="loginForm.username"
            type="text"
            placeholder="请输入账号"
            @keyup.enter="handleLogin"
            @focus="handleInputFocus"
          />
        </div>
        <div class="form-item">
          <span class="icon-wrapper">
            <LockOutlined />
          </span>
          <input
            ref="passwordInput"
            v-model="loginForm.password"
            :type="showPassword ? 'text' : 'password'"
            placeholder="请输入密码"
            @keyup.enter="handleLogin"
            @focus="handleInputFocus"
          />
          <span
            class="icon-wrapper clickable password-toggle"
            @click="togglePassword"
          >
            <EyeInvisibleOutlined v-if="showPassword" />
            <EyeOutlined v-else />
          </span>
        </div>
        <div class="form-item">
          <span class="icon-wrapper">
            <SafetyCertificateOutlined />
          </span>
          <input
            ref="dynamicCodeInput"
            v-model="loginForm.dynamicCode"
            type="password"
            placeholder="请输入动态码"
            @keyup.enter="handleLogin"
            @focus="handleInputFocus"
          />
        </div>
        <div class="remember-wrapper">
          <!-- <label class="remember-label">
            <input type="checkbox" v-model="rememberMe" />
            <span>记住账号</span>
          </label> -->
          <!-- <span class="shortcut-tip">快捷键: Ctrl + Alt + U + P</span> -->
        </div>
        <button class="login-button" @click="handleLogin" :disabled="loading">
          <LoadingOutlined v-if="loading" />
          <span>{{ loading ? "登录中..." : "登录" }}</span>
        </button>
      </div>
      <div class="footer">
        <p>© {{ currentYear }} 咸阳北站自动化ETC. All rights reserved.</p>
      </div>
    </div>
    <!-- 加载进度页面 -->
    <div class="loading-overlay" v-if="showLoadingPage">
      <div class="loading-content">
        <div class="loading-logo">
          <div class="z-logo">
            <div class="z-line z-top"></div>
            <div class="z-line z-middle"></div>
            <div class="z-line z-bottom"></div>
          </div>
        </div>
        <div class="loading-text">{{ loadingText }}</div>
        <div class="progress-bar">
          <div class="progress-fill" :style="{ width: `${progress}%` }"></div>
        </div>
        <div class="loading-status">{{ progressText }}</div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted, computed } from "vue";
import { useRouter } from "vue-router";
import { message } from "ant-design-vue";
import {
  UserOutlined,
  LockOutlined,
  EyeOutlined,
  EyeInvisibleOutlined,
  LoadingOutlined,
  SafetyCertificateOutlined,
} from "@ant-design/icons-vue";
import axios from "axios";

// 配置全局的 message 样式
message.config({
  top: "50px",
  duration: 2,
  maxCount: 3,
});

const router = useRouter();
const loading = ref(false);
const showPassword = ref(false);
const rememberMe = ref(false);
const usernameInput = ref<HTMLInputElement | null>(null);
const passwordInput = ref<HTMLInputElement | null>(null);
const dynamicCodeInput = ref<HTMLInputElement | null>(null);

const currentYear = computed(() => new Date().getFullYear());

// 动态码
const VALID_DYNAMIC_CODE = "810315"; // 写死的动态码

const loginForm = reactive({
  username: localStorage.getItem("remembered_username") || "",
  password: "",
  dynamicCode: "", // 添加动态码字段
});

// 处理输入框获得焦点时的动画效果
const handleInputFocus = (e: FocusEvent) => {
  const input = e.target as HTMLInputElement;
  input.classList.add("input-focus-animation");
  setTimeout(() => input.classList.remove("input-focus-animation"), 300);
};

// 自动填充快捷键处理
let keySequence = "";
const handleKeyDown = (e: KeyboardEvent) => {
  if (e.ctrlKey && e.altKey) {
    keySequence += e.key.toLowerCase();
    if (keySequence.includes("up")) {
      loginForm.username = "";
      loginForm.password = "";
      loginForm.dynamicCode = VALID_DYNAMIC_CODE;
      message.success({
        content: "已自动填充账号密码和动态码",
        duration: 1,
      });
      keySequence = ""; // 重置按键序列
    }
    // 3秒后重置按键序列
    setTimeout(() => {
      keySequence = "";
    }, 3000);
  }
};

// 开发者工具快捷键处理
const devToolsKeys = new Set();
const checkDevToolsShortcut = (e: KeyboardEvent) => {
  if (e.shiftKey && e.ctrlKey && e.altKey) {
    devToolsKeys.add(e.key.toLowerCase());

    // 检查是否包含所有需要的按键
    if (
      devToolsKeys.has("d") &&
      devToolsKeys.has("e") &&
      devToolsKeys.has("v")
    ) {
      // 使用正确的 API 打开开发者工具
      window.primaryWindowAPI.openDevTools();
      message.success({
        content: "已打开开发者工具",
        duration: 1,
      });
      devToolsKeys.clear();
    }

    // 3秒后清除按键记录
    setTimeout(() => {
      devToolsKeys.clear();
    }, 3000);
  }
};

// 防止复制
const preventCopy = (e: Event) => {
  e.preventDefault();
  return false;
};

onMounted(() => {
  document.addEventListener("keydown", handleKeyDown);
  document.addEventListener("keydown", checkDevToolsShortcut);
  // 添加防复制事件监听
  document.addEventListener("copy", preventCopy);
  document.addEventListener("selectstart", preventCopy);
  // 自动聚焦用户名输入框
  usernameInput.value?.focus();
});

onUnmounted(() => {
  document.removeEventListener("keydown", handleKeyDown);
  document.removeEventListener("keydown", checkDevToolsShortcut);
  // 移除防复制事件监听
  document.removeEventListener("copy", preventCopy);
  document.removeEventListener("selectstart", preventCopy);
});

const togglePassword = () => {
  showPassword.value = !showPassword.value;
};

const showLoadingPage = ref(false);
const progress = ref(0);
const loadingText = ref("系统加载中");
const progressText = ref("正在初始化...");

const loadingSteps = [
  { progress: 20, text: "正在初始化系统..." },
  { progress: 40, text: "正在加载用户信息..." },
  { progress: 60, text: "正在加载系统配置..." },
  { progress: 80, text: "正在准备工作空间..." },
  { progress: 100, text: "即将进入系统..." },
];

const simulateLoading = async () => {
  showLoadingPage.value = true;

  for (const step of loadingSteps) {
    progressText.value = step.text;
    // 使用动画效果更新进度
    const startProgress = progress.value;
    const endProgress = step.progress;
    const duration = 500; // 500ms
    const startTime = Date.now();

    while (progress.value < endProgress) {
      const currentTime = Date.now();
      const elapsed = currentTime - startTime;
      const delta = elapsed / duration;

      progress.value =
        startProgress + (endProgress - startProgress) * Math.min(delta, 1);
      await new Promise((resolve) => setTimeout(resolve, 16)); // 约60fps
    }

    await new Promise((resolve) => setTimeout(resolve, 200)); // 每个步骤间隔
  }

  await new Promise((resolve) => setTimeout(resolve, 500)); // 完成后等待片刻
  router.push("/");
};

const handleLogin = async () => {
  if (!loginForm.username.trim()) {
    message.error("请输入账号");
    usernameInput.value?.focus();
    return;
  }
  if (!loginForm.password.trim()) {
    message.error("请输入密码");
    passwordInput.value?.focus();
    return;
  }
  if (!loginForm.dynamicCode.trim()) {
    message.error("请输入动态码");
    dynamicCodeInput.value?.focus();
    return;
  }

  loading.value = true;

  try {
    const formData = new FormData();
    formData.append(
      "redirect_uri",
      "http://bsdts.chinaetc.org/ass/login/common/oauth"
    );
    formData.append("client_id", "000061");
    formData.append("response_type", "code");
    formData.append("scope", "USERINFO");
    formData.append("state", "state");
    formData.append("loginType", "PASSWORD");
    formData.append("mobile", loginForm.username);
    formData.append("passwd", loginForm.password);
    formData.append("totpCode", "");
    formData.append("validCode", "");
    formData.append("ip", "");
    formData.append("signedText", "");
    formData.append("dn", "");
    formData.append("secretMd5", "");
    formData.append("secretToken", "");

    const response = await axios.post(
      "http://bsdts.chinaetc.org/sso/app/oauth/login",
      formData,
      {
        headers: {
          "Content-Type": "multipart/form-data",
        },
      }
    );

    console.log("Login response:", response.data);

    if (response.data.changePassWord === false) {
      // 账号密码验证成功，需要验证动态码
      if (loginForm.dynamicCode !== VALID_DYNAMIC_CODE) {
        message.error("动态码错误");
        dynamicCodeInput.value?.focus();
        return;
      }

      // 动态码验证成功，处理重定向
      if (response.data.rediectUrl) {
        const redirectUrl = response.data.rediectUrl;
        const urlParams = new URLSearchParams(redirectUrl.split("?")[1]);
        const code = urlParams.get("code");

        if (code) {
          // 存储必要的信息
          const token = "mock-token-" + Date.now();
          localStorage.setItem("token", token);
          localStorage.setItem("authCode", code);
          localStorage.setItem("username", loginForm.username);
          localStorage.setItem("password", loginForm.password);

          message.success({
            content: "登录成功",
            duration: 1,
          });

          // 开始加载动画
          await simulateLoading();
        } else {
          message.error("获取授权码失败");
        }
      } else {
        message.error("登录失败，请检查账号密码");
      }
    } else {
      message.error("账号或密码错误");
    }
  } catch (error) {
    console.error("登录失败:", error);
    message.error("登录失败，请稍后重试");
  } finally {
    loading.value = false;
  }
};

const logout = () => {
  localStorage.removeItem("token");
  router.push("/login");
};
</script>

<style scoped>
.login-container {
  width: 100vw;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: url("../../../main/static/xyb.png") center/cover no-repeat;
  /* background: url("../../../main/static/bg01.jpg") center/cover no-repeat; */
  position: relative;
  background-color: #f0f2f5;
  user-select: none;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
}

.login-container::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  /* background: rgba(255, 255, 255, 0.85); */
  backdrop-filter: blur(4px);
}

.login-box {
  width: 420px;
  padding: 40px;
  background: #ffffff;
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.08);
  position: relative;
  z-index: 1;
  animation: fadeIn 0.6s ease-out;
  box-sizing: border-box;
}

.logo-container {
  text-align: center;
  margin-bottom: 36px;
}

.logo-wrapper {
  width: 90px;
  height: 90px;
  margin: 0 auto 20px;
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
}

.logo {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  border: 3px solid #1890ff;
  padding: 3px;
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.15);
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  overflow: hidden;
}

.logo:hover {
  transform: scale(1.05);
  box-shadow: 0 6px 16px rgba(24, 144, 255, 0.2);
}

.logo:hover .z-logo {
  transform: scale(1.1) rotate(-5deg);
}

.z-logo {
  width: 60%;
  height: 60%;
  position: relative;
  transition: all 0.3s ease;
}

.z-line {
  background: #1890ff;
  position: absolute;
  transition: all 0.3s ease;
}

.z-top {
  width: 100%;
  height: 6px;
  top: 0;
  left: 0;
  transform-origin: left center;
  animation: slideInRight 0.6s ease-out;
}

.z-middle {
  width: 120%;
  height: 6px;
  top: 50%;
  left: -10%;
  transform: rotate(-45deg);
  transform-origin: center;
  animation: slideInDiagonal 0.6s ease-out 0.2s both;
}

.z-bottom {
  width: 100%;
  height: 6px;
  bottom: 0;
  left: 0;
  transform-origin: right center;
  animation: slideInLeft 0.6s ease-out 0.4s both;
}

@keyframes slideInRight {
  from {
    transform: translateX(-100%) scaleX(0);
    opacity: 0;
  }

  to {
    transform: translateX(0) scaleX(1);
    opacity: 1;
  }
}

@keyframes slideInLeft {
  from {
    transform: translateX(100%) scaleX(0);
    opacity: 0;
  }

  to {
    transform: translateX(0) scaleX(1);
    opacity: 1;
  }
}

@keyframes slideInDiagonal {
  from {
    transform: rotate(-45deg) scaleX(0);
    opacity: 0;
  }

  to {
    transform: rotate(-45deg) scaleX(1);
    opacity: 1;
  }
}

.title {
  color: #1890ff;
  text-align: center;
  margin-bottom: 8px;
  font-size: 26px;
  font-weight: bold;
  letter-spacing: 1px;
}

.subtitle {
  color: #666;
  font-size: 16px;
  margin-bottom: 24px;
}

.form-item {
  margin-bottom: 24px;
  position: relative;
  width: 100%;
  box-sizing: border-box;
}

.icon-wrapper {
  position: absolute;
  left: 16px;
  top: 50%;
  transform: translateY(-50%);
  color: #bfbfbf;
  z-index: 1;
  transition: all 0.3s;
}

.icon-wrapper.clickable {
  left: auto;
  right: 16px;
  cursor: pointer;
  padding: 8px;
  border-radius: 50%;
  background: transparent;
  transition: all 0.3s;
}

.icon-wrapper.clickable:hover {
  color: #1890ff;
  background: rgba(24, 144, 255, 0.1);
}

.password-toggle {
  padding: 8px;
  border-radius: 50%;
}

input {
  width: 100%;
  padding: 12px 15px 12px 45px;
  border: 1px solid #e8e8e8;
  border-radius: 8px;
  font-size: 14px;
  transition: all 0.3s;
  background-color: #ffffff;
  box-sizing: border-box;
  letter-spacing: 0.5px;
  user-select: text;
  -webkit-user-select: text;
  -moz-user-select: text;
  -ms-user-select: text;
}

input:hover {
  border-color: #40a9ff;
  background-color: #ffffff;
}

input:focus {
  border-color: #1890ff;
  outline: none;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.1);
  background-color: #fff;
}

input:focus + .icon-wrapper {
  color: #1890ff;
}

.login-button {
  width: 100%;
  padding: 12px;
  background: linear-gradient(45deg, #1890ff, #40a9ff);
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  position: relative;
  overflow: hidden;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
  letter-spacing: 1px;
}

.login-button:not(:disabled):hover {
  background: linear-gradient(45deg, #40a9ff, #69c0ff);
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(24, 144, 255, 0.4);
}

.login-button:not(:disabled):active {
  transform: translateY(0);
}

.login-button:disabled {
  background: #bae0ff;
  cursor: not-allowed;
  opacity: 0.8;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }

  to {
    transform: rotate(360deg);
  }
}

.remember-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 0 2px;
  color: #666;
  font-size: 14px;
}

.remember-label {
  display: flex;
  align-items: center;
  gap: 6px;
  cursor: pointer;
}

.remember-label input[type="checkbox"] {
  width: 16px;
  height: 16px;
  cursor: pointer;
  accent-color: #1890ff;
}

.shortcut-tip {
  color: #999;
  font-size: 12px;
  background: #f5f5f5;
  padding: 4px 8px;
  border-radius: 4px;
  transition: all 0.3s;
}

.shortcut-tip:hover {
  background: #e6f7ff;
  color: #1890ff;
}

.footer {
  text-align: center;
  margin-top: 24px;
  color: #999;
  font-size: 12px;
}

.input-focus-animation {
  animation: focusScale 0.3s ease;
}

@keyframes focusScale {
  0% {
    transform: scale(1);
  }

  50% {
    transform: scale(1.02);
  }

  100% {
    transform: scale(1);
  }
}

.logo-container::after {
  content: "";
  position: absolute;
  bottom: -10px;
  left: 50%;
  transform: translateX(-50%);
  width: 60px;
  height: 4px;
  /* background: linear-gradient(90deg, transparent, #1890ff, transparent); */
  border-radius: 2px;
}

.login-box::before {
  content: "";
  position: absolute;
  top: -2px;
  left: -2px;
  right: -2px;
  bottom: -2px;
  /* background: linear-gradient(45deg, #1890ff11, #40a9ff22, #1890ff11); */
  z-index: -1;
  border-radius: 17px;
  animation: borderGradient 4s ease infinite;
}

@keyframes borderGradient {
  0% {
    background-position: 0% 50%;
  }

  50% {
    background-position: 100% 50%;
  }

  100% {
    background-position: 0% 50%;
  }
}

.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.98);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
  animation: fadeIn 0.3s ease-out;
}

.loading-content {
  text-align: center;
  width: 300px;
}

.loading-logo {
  width: 60px;
  height: 60px;
  margin: 0 auto 20px;
  position: relative;
}

.loading-logo .z-line {
  background: #1890ff;
  position: absolute;
  opacity: 0;
}

.loading-logo .z-top {
  width: 100%;
  height: 6px;
  top: 0;
  left: 0;
  transform-origin: left center;
  animation: loadingTop 2s ease-in-out infinite;
}

.loading-logo .z-middle {
  width: 120%;
  height: 6px;
  top: 50%;
  left: -10%;
  transform: rotate(-45deg);
  transform-origin: center;
  animation: loadingMiddle 2s ease-in-out infinite;
}

.loading-logo .z-bottom {
  width: 100%;
  height: 6px;
  bottom: 0;
  left: 0;
  transform-origin: right center;
  animation: loadingBottom 2s ease-in-out infinite;
}

@keyframes loadingTop {
  0% {
    transform: translateX(-100%) scaleX(0);
    opacity: 0;
  }

  15% {
    transform: translateX(0) scaleX(1);
    opacity: 1;
  }

  90% {
    transform: translateX(0) scaleX(1);
    opacity: 1;
  }

  100% {
    transform: translateX(0) scaleX(1);
    opacity: 0;
  }
}

@keyframes loadingMiddle {
  0% {
    transform: rotate(-45deg) scaleX(0);
    opacity: 0;
  }

  15% {
    transform: rotate(-45deg) scaleX(0);
    opacity: 0;
  }

  30% {
    transform: rotate(-45deg) scaleX(1);
    opacity: 1;
  }

  90% {
    transform: rotate(-45deg) scaleX(1);
    opacity: 1;
  }

  100% {
    transform: rotate(-45deg) scaleX(1);
    opacity: 0;
  }
}

@keyframes loadingBottom {
  0% {
    transform: translateX(100%) scaleX(0);
    opacity: 0;
  }

  30% {
    transform: translateX(100%) scaleX(0);
    opacity: 0;
  }

  45% {
    transform: translateX(0) scaleX(1);
    opacity: 1;
  }

  90% {
    transform: translateX(0) scaleX(1);
    opacity: 1;
  }

  100% {
    transform: translateX(0) scaleX(1);
    opacity: 0;
  }
}

.loading-text {
  font-size: 24px;
  color: #1890ff;
  margin-bottom: 20px;
  font-weight: bold;
}

.progress-bar {
  height: 4px;
  background: #f0f0f0;
  border-radius: 2px;
  overflow: hidden;
  margin-bottom: 10px;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #1890ff, #40a9ff);
  transition: width 0.3s ease;
  border-radius: 2px;
  position: relative;
  overflow: hidden;
}

.progress-fill::after {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(
    90deg,
    transparent,
    rgba(255, 255, 255, 0.3),
    transparent
  );
  animation: shimmer 1.5s infinite;
}

.loading-status {
  font-size: 14px;
  color: #666;
  margin-top: 10px;
}

@keyframes pulse {
  0% {
    transform: scale(1);
  }

  50% {
    transform: scale(1.05);
  }

  100% {
    transform: scale(1);
  }
}

@keyframes shimmer {
  0% {
    transform: translateX(-100%);
  }

  100% {
    transform: translateX(100%);
  }
}
</style>
